package com.housekeeperapp.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import com.housekeeperapp.MainApplication;
import com.reactnativenavigation.NavigationApplication;
import com.reactnativenavigation.controllers.IntentDataHandler;
import com.reactnativenavigation.controllers.NavigationCommandsHandler;
import com.reactnativenavigation.events.Event;
import com.reactnativenavigation.events.EventBus;
import com.reactnativenavigation.events.JsDevReloadEvent;
import com.reactnativenavigation.events.Subscriber;
import com.reactnativenavigation.layouts.Layout;
import com.reactnativenavigation.layouts.LayoutFactory;
import com.reactnativenavigation.params.ActivityParams;
import com.reactnativenavigation.params.AppStyle;
import com.reactnativenavigation.react.ReactGateway;
import com.reactnativenavigation.utils.OrientationHelper;

/**
 * Created by wsj on 2017/11/20.
 */

public class BaseActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler, Subscriber, PermissionAwareActivity {

    private ActivityParams activityParams;
    private Layout layout;

    private InputMethodManager manager;

    protected Activity mActivity;

    @Nullable
    private PermissionListener mPermissionListener;

    public String screenId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!NavigationApplication.instance.isReactContextInitialized()) {
            NavigationApplication.instance.startReactContextOnceInBackgroundAndExecuteJS();
            return;
        }

        mActivity = this;
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        activityParams = NavigationCommandsHandler.parseActivityPageParams(getIntent());
        // activity 标示
        if(activityParams.screenParams != null){
            screenId = activityParams.screenParams.getScreenInstanceId();
        }

        createLayout();
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (isFinishing() || !NavigationApplication.instance.isReactContextInitialized()) {
            return;
        }

        getReactGateway().onResumeActivity(this, this);
        EventBus.instance.register(this);

        //出现View时
        if(activityParams.screenParams != null){
            MainApplication.getInstance().getEventEmitter().sendNavigatorEvent("willAppear", activityParams.screenParams.getNavigatorEventId());
            MainApplication.getInstance().getEventEmitter().sendNavigatorEvent("didAppear", activityParams.screenParams.getNavigatorEventId());
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        getReactGateway().onPauseActivity();
        EventBus.instance.unregister(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getReactGateway().onNewIntent(intent);
    }

    @Override
    protected void onDestroy() {
        destroyLayouts();
//        destroyJsIfNeeded();
        super.onDestroy();
    }

    private void destroyLayouts() {

        if (layout != null) {
            layout.destroy();
            layout = null;
        }
    }

    private void createLayout() {
        if(activityParams.type == null){
            return;
        }

        layout = LayoutFactory.create(this, activityParams);
        //设置背景
        layout.asView().setBackgroundColor(Color.parseColor("#f3f3f3"));

        setContentView(layout.asView());
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }


    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

    public Layout getLayout(){
        return layout;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return getReactGateway().onKeyUp(getCurrentFocus(), keyCode) || super.onKeyUp(keyCode, event);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getReactGateway().onActivityResult(requestCode, resultCode, data);
//        NavigationApplication.instance.getActivityCallbacks().onActivityResult(requestCode, resultCode, data);
    }

    private ReactGateway getReactGateway() {
        return NavigationApplication.instance.getReactGateway();
    }

    @Override
    public void onEvent(Event event) {
        if (event.getType().equals(JsDevReloadEvent.TYPE)) {
            handleJsDevReloadEvent();
        }
    }

//    @Override
//    public void onConfigurationChanged(Configuration newConfig) {
//        OrientationHelper.onConfigurationChanged(newConfig);
////        NavigationApplication.instance.getActivityCallbacks().onConfigurationChanged(newConfig);
//        super.onConfigurationChanged(newConfig);
//    }

    private void handleJsDevReloadEvent() {
        if(layout != null) {
            layout.destroy();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
        mPermissionListener = listener;
        requestPermissions(permissions, requestCode);
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
            mPermissionListener = null;
        }
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }

    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
